package com.foreknow.demo14;

import javax.xml.transform.Result;
import java.sql.*;

/**
 * PreparedStatement预处理(预编译)： 可以执行动态的SQL语句
 */
public class PreparedStatementDemo {
    public static void main(String[] args) {
        try {
            //1. 加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2. 获取连接Connection
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo_pro","root","123456");
            //3. 获取PreparedStatement对象
//            PreparedStatement pstmt = conn.prepareStatement("insert into users(name,email) values(?,?)");
            PreparedStatement pstmt = conn.prepareStatement("select * from users where name=? and email=?");
            //需要将？替换具体的值  1表示的是第几个？
            pstmt.setString(1,"yamaha");
            pstmt.setString(2,"yamaha@163.com");
            //执行更新
            //int isRight = pstmt.executeUpdate();
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                Users users = new Users();
                //将当前行数据保存到对象中
                users.setUserId(rs.getInt("user_id"));
                users.setName(rs.getString("name"));
                users.setEmail(rs.getString("email"));
                System.out.println(users.getName()+"---" + users.getEmail());
            }
            //关闭资源
            rs.close();
            pstmt.close();
            conn.close();

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
}
